<template>
  <div>
    <label class="el-radio">
        <span class="el-radio__input" :class="dynamicClass">
            <span class="el-radio__inner"></span>
            <input type="radio" :checked="computedValue == label" :value="label" @change="handleChange" class="el-radio__original">
        </span>
        <span class="el-radio__label">
            <slot></slot>
        </span>
    </label>
  </div>
</template>

<script>
import { computed, defineComponent, inject } from 'vue-demi'
export default defineComponent({
    name:'el-radio',
    props:{
        value:{
            // 扩展 v-model 语法糖
            type:String,
            default:""
        },
        label:{
            // 绑定到 原生radio的value上
            type:String,
            default:""
        }
    },
    
    setup(props,{emit}){
        const RadioGroup = inject("RadioGroup","")
        const handleChange = (e)=>{
            // 扩展 v-model 语法糖
            if(RadioGroup){
                // 如果是组radio时，则应由父组件<RadioGroup>来向上emit('input')事件
                RadioGroup.$emit("input",e.target.value)
                return;
            }
            // 扩展 v-model 语法糖(单radio组件使用时)
            emit("input",e.target.value)
        }
        const computedValue = computed(()=>{
            if(RadioGroup){
                return RadioGroup.value
            }else{
                return props.value
            }
        })
        const dynamicClass = computed(()=>{
            return {
                'is-checked':computedValue.value === props.label
            }
        })
        return {
            handleChange,
            dynamicClass,
            computedValue
        }
    }
})
</script>

<style lang="scss">
@import "./index.scss"
</style>